﻿using System;
using System.Collections.Generic;
using System.Linq;

using Fuse8.DomainFramework.Common.Locator;
using Fuse8.DomainFramework.DataAccess;
using Fuse8.DomainFramework.DataAccess.SqlDatabase;

using Fuse8.ContentManagementFramework.Domain.Commands;
using Fuse8.ContentManagementFramework.Domain.Special;
using Fuse8.ContentManagementFramework.Domain;

namespace Fuse8.ContentManagementFramework.DataAccess.SqlAccess.Commands
{
    internal class CmsContentGetForContentTypeDataCommand : CmsContentGetForContentTypeCommand
    {
        public override CmsContentContainer ExecuteOne()
        {
            CmsContentContainer result = null;

            var factory = DependencyServiceLocator.Current.GetInstance<IUnitOfWorkFactory<CmsContentContainer>>();

            var currentUnitOfWork = factory.Get(false) as SqlUnitOfWork<CmsContentContainer>;

            if (currentUnitOfWork != null)
            {
                var mapper = DependencyServiceLocator.Current.GetInstance<ISqlEntityDataMapper<CmsContent, int>>();

                var data = SqlUtility<CmsContent, int>.ExecuteReader(
                        currentUnitOfWork.Connection,
                        currentUnitOfWork.Transaction,
                         "cms_sp_Content_Select_For_ContentType",
                        new
                        {
                            SiteGroupId = CommandParameter.SiteGroupId,
                            SiteId = CommandParameter.SiteId,
                            ContentTypeId = CommandParameter.Id,
                            CurrentPage = CommandParameter.CurrentView,
                            PageCapacity = CommandParameter.TotalOnTheView
                        },
                        mapper).ToList();

                if (data != null)
                {
                    result = new CmsContentContainer
                    {
                        Contents = data.ToList(),
                        TotalCount = data.Count()
                    };
                }
            }

            return result;
        }
    }
}
